﻿using RabbitMQ.Client;
using System;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var factory = new ConnectionFactory
            {
                HostName = "127.0.0.1",
                Port = 5672,
                UserName = "admin",
                Password = "admin"
            };

            var connection = factory.CreateConnection();
            connection.ConnectionUnblocked += (sender, e) =>
            {
                //解除阻塞
            };
            connection.ConnectionBlocked += (sender, e) =>
            {
                //阻塞
            };
            var channel = connection.CreateModel();

            //Publish(channel);

            Consumer(channel);

            Console.ReadKey();

        }

        private static void Connection_ConnectionBlocked(object sender, RabbitMQ.Client.Events.ConnectionBlockedEventArgs e)
        {
            throw new NotImplementedException();
        }

        private static void Connection_ConnectionUnblocked(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 订阅
        /// </summary>
        /// <param name="channel"></param>
        static void Consumer(IModel channel)
        {
            //主动拉取
            var result = channel.BasicGet("mytest", true);

            var msg = Encoding.UTF8.GetString(result.Body.ToArray());

            Console.WriteLine(msg);
        }
        /// <summary>
        /// 发布
        /// </summary>
        /// <param name="channel"></param>
        static void Publish(IModel channel)
        {
            //队列名称,是否持久化,是否排外,
            channel.QueueDeclare("mytest", true, false, false, null);

            channel.BasicPublish(string.Empty, "mytest", null, Encoding.UTF8.GetBytes("你好"));

        }
    }
}
